#!/usr/bin/env python
#coding=UTF-8
'''
Created on 2010-11-4

@author: zarra
'''
import cv
from common import Question

def hist(image):
    '''返回归一化后的直方图数组'''
    result = [0.0 for i  in range(256)]
    width,height = image.width,image.height
    count = width * height#图像的总像素

    for h in range(height):
        for w in range(width):           
            index = int(image[h,w])
            result[ index ]+=1.0
            
    return [i/count for i in result]
    
    
def cumulative_hist(image):
    '''返回累计直方图'''
    h = hist(image)
    result = list()
    for i in range(len(h)):
        if i == 0:
            result.append(h[i])
        else:
            result.append(result[i-1]+h[i])
    return result
    

def hist_equal(image):
    '''返回被直方图均衡化后的图像 (使用累计分布函数)'''
    c_hist= cumulative_hist(image)
    N=len(c_hist)-1

    sk_tk =  [ int(round(N*i)) for i in c_hist]
    result = cv.CreateImage((image.width,image.height), cv.IPL_DEPTH_8U, 1)
    
    width,height = image.width,image.height
    for h in range(height):
        for w in range(width):
            
            index = int(image[h,w])#原图像的灰度级
            result[ h,w ] = sk_tk[index]#映射到新的灰度

    return result
    
def draw_hist(src):
    ''' 返回一个可示图像  内容为输入图像的直方图'''
    h = hist(src)
    
    result = cv.CreateImage((256*2,100), cv.IPL_DEPTH_8U, 1)
    cv.Zero(result)
    for i in range(len(h)):
        v=int(round(h[i]*1000))
        if v>=100:
            v=100
        #print v
        cv.Line(result, (i*2,99), (i*2,99-v),(255,255,255))
    return result

class Q1(Question):
    def __init__(self,image,name,m='show'):
        super(self.__class__,self).__init__(name,image,m)
                
    def action(self):
        image = self.image
        new_image = hist_equal(image)
        h_image=draw_hist(image)
    
        self.display(image,'image')
        self.display(new_image,'after_hist_equal')
    
        out = cv.CreateImage((image.width,image.height), cv.IPL_DEPTH_8U, 1)
        cv.EqualizeHist(image, out)
    
        self.display(out,'use_opencv_hist_equal')
    
        self.display(h_image,'hist')
    
        eh=draw_hist(new_image)
        self.display(eh,'equal_hist')
    
    
if __name__ == '__main__':
    q = Q1('fig1.jpg','Q1','save')
    q()
    q = Q1('fig2.jpg','Q12','save')
    q()

    